package com.caiwm.view.panel;

import com.caiwm.common.ServerResponse;
import com.caiwm.entity.Student;
import com.caiwm.service.impls.StudentService;
import com.caiwm.view.StudentView;
import com.caiwm.view.dialog.CaiwmDialog;
import com.caiwm.view.table.StudentTableModel;

import javax.swing.*;
import javax.swing.event.MenuListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 * ━━━━━━神兽出没━━━━━━
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃  神兽保佑
 * 　　　　┃　　　┃  代码无bug
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━感觉萌萌哒━━━━━━
 * </pre>
 *
 * @author shiqla
 * @Desc ${DESC}
 * @Date 2019/1/8/008
 */
public class MenuPanel extends CaiwmDialog implements ActionListener {

    private StudentView studentView;

    private JMenuBar jMenuBar;

    private JMenuItem importMenuItem;
    private JMenuItem saveMenuItem;
    private JMenuItem saveAsMenuItem;
    private JMenu fileMenu;


    private JMenuItem addMenuItem;
    private JMenuItem updateMenuItem;
    private JMenuItem deleteMenuItem;
    private JMenu editMenu;


    private JMenuItem helpMenuItem;
    private JMenuItem aboutMenuItem;
    private JMenu helpMenu;

    private StudentService studentService;

    private FileDialog importDialog;
    private FileDialog saveDialog;

    public MenuPanel(StudentView studentView) {
        this.studentView = studentView;

        jMenuBar = new JMenuBar();

        importMenuItem = new JMenuItem("导入");
        saveMenuItem = new JMenuItem("保存");
        saveAsMenuItem = new JMenuItem("另存为");
        fileMenu = new JMenu("文件");

        addMenuItem = new JMenuItem("新增学生信息");
        updateMenuItem = new JMenuItem("修改学生信息");
        deleteMenuItem = new JMenuItem("删除学生信息");
        editMenu = new JMenu("编辑");

        helpMenuItem = new JMenuItem("帮助");
        aboutMenuItem = new JMenuItem("关于");
        helpMenu = new JMenu("帮助");

        saveDialog = new FileDialog(this.studentView.getjFrame(), "另存为", FileDialog.SAVE);
        importDialog = new FileDialog(this.studentView.getjFrame(), "导入", FileDialog.LOAD);

        studentService = new StudentService();
    }

    public JMenuBar renderMenuBar() {

        fileMenu.add(importMenuItem);
        fileMenu.add(saveMenuItem);
        fileMenu.add(saveAsMenuItem);

        editMenu.add(addMenuItem);
//        editMenu.add(updateMenuItem);
        editMenu.add(deleteMenuItem);

        helpMenu.add(helpMenuItem);
        helpMenu.add(aboutMenuItem);

        jMenuBar.add(fileMenu);
        jMenuBar.add(editMenu);
        jMenuBar.add(helpMenu);

        this.bindListener();

        return this.jMenuBar;
    }

    private void bindListener() {

        this.saveMenuItem.addActionListener(this);
        this.importMenuItem.addActionListener(this);
        this.saveAsMenuItem.addActionListener(this);

        this.helpMenuItem.addActionListener(this);
        this.aboutMenuItem.addActionListener(this);

        this.deleteMenuItem.addActionListener(this);
        this.addMenuItem.addActionListener(this);
    }

    public StudentView getStudentView() {
        return studentView;
    }

    private List<Student> getStudentList(JTable table) {

        List<Student> list = new ArrayList<Student>();
        int rows = table.getRowCount();

        for (int i = 0; i < rows; i++) {
            Student student = new Student();

            student.setId(Integer.valueOf(table.getValueAt(i, 0).toString()));
            student.setName(table.getValueAt(i, 1).toString());
            if (table.getValueAt(i, 2).toString().equals("*")) {
                student.setAge(0);
            } else {
                student.setAge(Integer.valueOf(table.getValueAt(i, 2).toString()));
            }
            student.setSex(table.getValueAt(i, 3).toString());
            student.setPhone(table.getValueAt(i, 4).toString());
            student.setParentPhone(table.getValueAt(i, 5).toString());
            student.setParentName(table.getValueAt(i, 6).toString());
            student.setAddress(table.getValueAt(i, 7).toString());
            student.setGrade(table.getValueAt(i, 8).toString());
            student.setStudentClass(table.getValueAt(i, 9).toString());

            list.add(student);
        }

        return list;
    }

    public void actionPerformed(ActionEvent e) {

        String commandStr = e.getActionCommand();

        if (commandStr.equals("保存")) {
            JTable table = this.studentView.getDataViewPanel().getjTable();

            List<Student> list = this.getStudentList(table);
            ServerResponse serverResponse = studentService.updateBatch(list);
            if (serverResponse.isSuccess()) {
                String message = serverResponse.getMessage();
                this.successMessageDialog(message);
            } else {
                this.errorMessageDialog(serverResponse.getMessage());
            }
        } else if (commandStr.equals("帮助")) {
            System.out.println("更多帮助请访问: https://www.baidu.com");
            this.successMessageDialog("更多帮助请访问: https://www.baidu.com");
        } else if (commandStr.equals("关于")) {
            this.successMessageDialog("这里是蔡文敏同学的JAVA期末作业");
        } else if (commandStr.equals("删除学生信息")) {
            JTable table = this.studentView.getDataViewPanel().getjTable();
            int[] selectRow = table.getSelectedRows();

            if (selectRow.length == 0) {
                errorMessageDialog("请选择需要删除的数据!");
            } else {
                StudentTableModel studentTableModel = (StudentTableModel) table.getModel();

                List<Integer> idList = new ArrayList<Integer>();

                for (int i : selectRow) {
                    String idStr = table.getValueAt(i, 0).toString();
                    Integer id = Integer.valueOf(idStr);
                    idList.add(id);
                }

                ServerResponse serverResponse = studentService.deleteById(idList);
                if (serverResponse.isSuccess()) {
                    successMessageDialog(serverResponse.getMessage());

                    for (int i = selectRow.length - 1; i >= 0; i--) {
                        studentTableModel.removeRow(selectRow[i]);
                    }
                } else {
                    errorMessageDialog(serverResponse.getMessage());
                }
            }
        } else if (commandStr.equals("另存为")) {
            this.saveDialog.setVisible(true);
            JTable table = this.studentView.getDataViewPanel().getjTable();
            List<Student> list = this.getStudentList(table);

            String dirpath = this.saveDialog.getDirectory();//获取打开文件路径并保存到字符串中。
            String fileName = this.saveDialog.getFile();//获取打开文件名称并保存到字符串中

            File file = new File(dirpath, fileName);

            StringBuilder stringBuilder = new StringBuilder();
            for (Student student : list) {
                String str = student.getId() + "#" + student.getName() + "#" +
                        student.getAge() + "#" + student.getSex() + "#" +
                        student.getPhone() + "#" + student.getParentPhone() + "#" +
                        student.getParentName() + "#" + student.getAddress() + "#" +
                        student.getGrade() + "#" + student.getStudentClass() + "\n";
                stringBuilder.append(str);
            }
            BufferedWriter bufferedWriter;
            try {
                bufferedWriter = new BufferedWriter(new FileWriter(file));
                bufferedWriter.write(stringBuilder.toString());
                bufferedWriter.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } else if (commandStr.equals("导入")) {
            this.importDialog.setVisible(true);
            JTable table = this.studentView.getDataViewPanel().getjTable();
            StudentTableModel studentTableModel = (StudentTableModel) table.getModel();

            String dirpath = this.importDialog.getDirectory();//获取打开文件路径并保存到字符串中。
            String fileName = this.importDialog.getFile();//获取打开文件名称并保存到字符串中

            System.out.println(dirpath + " " + fileName);

            File file = new File(dirpath, fileName);

            List<Object[]> list = new ArrayList<Object[]>();
            try {
                BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
                String temp = null;
                while ((temp = bufferedReader.readLine()) != null) {
                    if (temp.equals("") || temp.length() == 0) {
                        continue;
                    }
                    Object[] objects = temp.split("#");
                    list.add(objects);
                }
                bufferedReader.close();
                studentTableModel.setRowCount(0);
                for (int i = 0; i < list.size(); i++) {
                    studentTableModel.insertRow(i, list.get(i));
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }

        } else if (commandStr.equals("新增学生信息")) {
            JTable table = this.studentView.getDataViewPanel().getjTable();
            StudentTableModel studentTableModel = (StudentTableModel) table.getModel();
            studentTableModel.insertRow(0, new Object[]{0, "*", "*", "", "", "*", "*", "*", "*", "*"});
        }
    }
}
